const {Publish, User, PublishLike, PublishComment} = require("../database/index");
const {sendResponse} = require("../untils");
const {mockPublish} = require("./mock");
const {sequelize} = require("../database");

// -------------------------- 核心功能实现 --------------------------

/**
 * 发布信息
 */
const addPublish = async (ctx) => {
    try {
        const {content, imgs, user_id} = ctx.request.body;

        // 参数验证：至少需要内容或图片
        if (!content && !imgs) {
            return sendResponse(ctx, 400, "发布内容或图片至少需要一项", []);
        }

        // 验证用户ID是否存在
        if (!user_id) {
            return sendResponse(ctx, 400, "缺少用户ID参数", []);
        }

        const publish = await Publish.create({
            content,
            imgs: JSON.stringify(imgs),
            user_id  // 补充用户ID字段（原代码遗漏）
        });

        sendResponse(ctx, 200, "发布信息成功", publish);
    } catch (error) {
        console.error("发布信息异常:", error);
        sendResponse(ctx, 500, "发布信息失败", error.message);
    }
};

/**
 * 批量添加发布信息
 * @param {Array} publishList - 发布信息列表
 */
const bathAddPublish = async (ctx) => {
    try {
        const publishList = mockPublish;
        publishList.forEach(publishItem => {
            publishItem.imgs = JSON.stringify(publishItem.imgs);
        })
        // const { publishList } = ctx.request.body;

        // 参数验证：至少需要发布列表
        if (!publishList || publishList.length === 0) {
            return sendResponse(ctx, 400, "发布列表不能为空", []);
        }

        // 批量创建发布信息
        const publish = await Publish.bulkCreate(publishList);

        sendResponse(ctx, 200, "批量添加发布信息成功", publish);
    } catch (error) {
        console.error("批量添加发布信息异常:", error);
    }
};

/**
 * 修改发布信息
 */
const editPublish = async (ctx) => {
    try {
        const {publish_id, content, imgs} = ctx.request.body;

        // 参数验证：必须提供ID
        if (!publish_id) {
            return sendResponse(ctx, 400, "修改发布信息失败,缺少参数p_id", []);
        }

        // 参数验证：至少需要修改一项内容
        if (content === undefined && imgs === undefined) {
            return sendResponse(ctx, 400, "至少需要提供一项修改内容", []);
        }

        const [affectedCount] = await Publish.update(
            {content, imgs},
            {where: {publish_id}}
        );

        if (affectedCount > 0) {
            sendResponse(ctx, 200, "修改发布信息成功", {affectedCount});
        } else {
            sendResponse(ctx, 404, "未找到对应发布信息或内容未变更", []);
        }
    } catch (error) {
        console.error("修改发布信息异常:", error);
        sendResponse(ctx, 500, "修改发布信息失败", error.message);
    }
};

/**
 * 删除发布信息
 */
const deletePublish = async (ctx) => {
    try {
        const {publish_id} = ctx.request.body;

        // 参数验证：必须提供ID
        if (!publish_id) {
            return sendResponse(ctx, 400, "删除发布信息失败,缺少参数p_id", []);
        }

        const affectedCount = await Publish.destroy({
            where: {publish_id}
        });

        if (affectedCount > 0) {
            sendResponse(ctx, 200, "删除发布信息成功", {affectedCount});
        } else {
            sendResponse(ctx, 404, "未找到对应发布信息", []);
        }
    } catch (error) {
        console.error("删除发布信息异常:", error);
        sendResponse(ctx, 500, "删除发布信息失败", error.message);
    }
};

/**
 * 获取发布信息
 */
const getPublish = async (ctx) => {
    try {
        let {currentPage, pageSize, user_id} = ctx.request.body;
        // 处理默认分页参数
        currentPage = currentPage ? parseInt(currentPage) : 1;
        pageSize = pageSize ? parseInt(pageSize) : null;
        const offset = (currentPage - 1) * pageSize;

        const {count: total, rows: publish} = await Publish.findAndCountAll({
            offset,
            limit: pageSize,
            order: [['createdAt', 'desc']], //默认时间降序
            // 关联查询用户信息
            include: [{
                model: User,
                attributes: ['name', 'src'],
                required: true // 只返回有有效用户的发布
            }],
            // 返回字段
            attributes: [
                'publish_id', 'content', 'imgs', 'likeCount', 'commentCount',
                'createdAt', 'updatedAt',
                // 关键：通过子查询判断当前用户是否点赞
                [
                    sequelize.literal(`
            EXISTS(
              SELECT 1 FROM publish_like 
              WHERE publish_like.publish_id = Publish.publish_id 
              AND publish_like.user_id = ${user_id || 'NULL'}
            )
          `),
                    'liked' // 生成liked字段：true/false
                ]
            ]
        });

        sendResponse(ctx, 200, "获取发布信息成功", {
            data: publish,
            totalCount: total
        });
    } catch (error) {
        console.error("获取发布信息异常:", error);
        sendResponse(ctx, 500, "获取发布信息失败", error.message);
    }
};

// 点赞功能
const likePublish = async (ctx) => {
    try {
        const {publish_id, user_id} = ctx.request.body;

        if (!publish_id || !user_id) {
            return sendResponse(ctx, 400, "缺少发布ID或用户ID", []);
        }

        // 检查是否已经点赞
        const existingLike = await PublishLike.findOne({
            where: {publish_id, user_id}
        });

        if (existingLike) {
            // 取消点赞
            await existingLike.destroy();
            // 更新发布的点赞数
            await Publish.decrement('likeCount', {where: {publish_id}});
            return sendResponse(ctx, 200, "取消点赞成功", {liked: false});
        } else {
            // 新增点赞
            await PublishLike.create({publish_id, user_id});
            // 更新发布的点赞数
            await Publish.increment('likeCount', {where: {publish_id}});
            return sendResponse(ctx, 200, "点赞成功", {liked: true});
        }
    } catch (error) {
        console.error("点赞异常:", error);
        sendResponse(ctx, 500, "点赞操作失败", error.message);
    }
};

// 获取评论列表
const getComments = async (ctx) => {
    try {
        const {publish_id} = ctx.request.body;

        if (!publish_id) {
            return sendResponse(ctx, 400, "缺少发布ID", []);
        }

        const comments = await PublishComment.findAndCountAll({
            where: {publish_id},
            order: [['createdAt', 'desc']],
            include: [{
                model: User,
                attributes: [ 'id', 'name', 'src']
            }]
        });

        sendResponse(ctx, 200, "获取评论成功", comments.rows);
    } catch (error) {
        console.error("获取评论异常:", error);
        sendResponse(ctx, 500, "获取评论失败", error.message);
    }
};

// 添加评论
const addComment = async (ctx) => {
    try {
        const {publish_id, user_id, parent_id, content} = ctx.request.body;

        if (!publish_id || !user_id || !content) {
            return sendResponse(ctx, 400, "发布ID、用户ID和评论内容不能为空", []);
        }

        // 创建评论
        const comment = await PublishComment.create({
            publish_id,
            user_id,
            parent_id,
            content
        });

        // 更新发布的评论数
        await Publish.increment('commentCount', {where: {publish_id}});

        sendResponse(ctx, 200, "评论成功", comment);
    } catch (error) {
        console.error("添加评论异常:", error);
        sendResponse(ctx, 500, "评论失败", error.message);
    }
};


// -------------------------- 路由配置 --------------------------
const publishRoutes = [
    {type: 'post', url: '/publish/addPublish', method: addPublish},
    {type: 'post', url: '/publish/bathAddPublish', method: bathAddPublish},
    {type: 'post', url: '/publish/editPublish', method: editPublish},
    {type: 'post', url: '/publish/deletePublish', method: deletePublish},
    {type: 'post', url: '/publish/getPublish', method: getPublish},
    {type: 'post', url: '/publish/likePublish', method: likePublish},
    {type: 'post', url: '/publish/getComments', method: getComments},
    {type: 'post', url: '/publish/addComment', method: addComment}
];

module.exports = publishRoutes;
